package com.hlbspringcloud.mq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Date;

/**
 * @Author huanglibin
 * @Project mq
 * @Description 工作队列 消费者2 消息应答机制
 * @Date 2020-12-02-16-28-40
 * @Version 1.0
 */
public class WorkFairReceiver2 {
    /**
     * 队列名称
     */
    public static final String QUEUE_NAME="work fair query";

    /**
     * 接收消息
     * @throws Exception
     */
    public void receiveMessage()throws Exception{
        //1、获取连接
        Connection rabbitmqConnection = RabbitmqUntil.getRabbitmqConnection();
        //2、获取管道
        final Channel channel = rabbitmqConnection.createChannel();
        //3、创建队列（如果队列已存在，则不进行处理）
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        //4、设置每次处理息不超过1条
        channel.basicQos(1);
        //5、创建消费用户
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("公平分发接收者2:"+System.currentTimeMillis()+"  "+new String(body,"utf-8"));
                try {
                    Thread.sleep(10000);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    //处理完成后给rabbitmq一个应答响应
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        /**
         * 6、监听rabbitmq队列信息（此时程序会自动堵塞，当有数据到达时，处理相应的数据）
         * 参数1：队列名
         * 参数2：是否自动问答（设置为非自动问答）
         * 参数3：消费用户
         */
        channel.basicConsume(QUEUE_NAME,false,consumer);
    }

    public static void main(String[] args)throws Exception {
        WorkFairReceiver2 workFairReceiver2 = new WorkFairReceiver2();
        workFairReceiver2.receiveMessage();
    }
}
